package com.aplink.generic.xmlparser;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.text.TextUtils;

import com.aplink.generic.pojo.formdesign.Column;
import com.aplink.generic.pojo.formdesign.SelectWhere;

public class SelectWhereParser {
	private static final String COLUMN = "column";
	private static final String DEFAULT_VALUE = "defaultValue";
	private static final String OBJECT_LOAD_BY = "selectWhere";
	private static final String PASSED_COLUMN_ID = "passedColumnID";
	private static final String TARGET = "target";

	public static SelectWhere parsse(Node node) {
		final SelectWhere objectLoadBy = new SelectWhere();
		Element element = (Element) node;
		NodeList nodes = element
				.getElementsByTagName(SelectWhereParser.OBJECT_LOAD_BY);
		if (nodes.getLength() == 0) {
			return objectLoadBy;
		}
		node = nodes.item(0);
		if (node.hasAttributes()) {
			final String target = XmlPaserUtil.getAttrValue(node,
					SelectWhereParser.TARGET);
			if (!TextUtils.isEmpty(target)) {
				objectLoadBy.setTargetClass(target);
			}
		}
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			element = (Element) node;
			nodes = element.getElementsByTagName(SelectWhereParser.COLUMN);
			for (int i = 0; i < nodes.getLength(); i++) {
				final Column column = new Column();
				final Node nodeColumn = nodes.item(i);
				String defaultValue = null;
				if (nodeColumn.hasAttributes()) {
					defaultValue = XmlPaserUtil.getAttrValue(nodeColumn,
							SelectWhereParser.DEFAULT_VALUE);
					column.setDefaultValue(defaultValue);
					defaultValue = XmlPaserUtil.getAttrValue(nodeColumn,
							SelectWhereParser.PASSED_COLUMN_ID);
					column.setPassedColumnID(defaultValue);

				}
				final String columnValue = XmlPaserUtil
						.getNodeValue(nodeColumn);
				column.setColumnName(columnValue);
				objectLoadBy.add(column);
			}
		}
		return objectLoadBy;
	}
}
